<template>
    <navigation></navigation>
    <div class="bg-gray-50 min-h-fit py-4"> <!-- 修改min-h-screen为min-h-fit，减少内边距 -->
        <div class="max-w-4xl mx-auto px-4 sm:px-6">
            <div class="max11">
                <!-- 面包屑导航 -->
                <nav class="flex items-center justify-center gap-2 mb-4 text-gray-600 text-sm sm:text-base">
                    <router-link to="/" class="hover:text-primary transition-colors">首页</router-link>
                    <el-icon>
                        <ArrowRight class="text-xs" />
                    </el-icon>
                    <router-link to="#" class="hover:text-primary transition-colors">个人中心</router-link>
                    <el-icon>
                        <ArrowRight class="text-xs" />
                    </el-icon>
                    <span class="text-gray-400">用户信息</span>
                </nav>
            </div>
            
            <!-- 用户信息卡片 - 减少内边距 -->
            <el-card class="mb-4 shadow-sm hover:shadow-md transition-shadow">
                <div class="flex flex-col md:flex-row gap-4 items-center p-3 sm:p-4">
                    <div class="relative">
                        <el-avatar :size="80" src="/src/assets/img/center.gif" 
                                  class="border-4 border-blue-50 shadow-sm" />
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3 w-full mt-2 md:mt-0">
                        <div v-for="(item, index) in userInfo" :key="index" 
                             class="text-center sm:text-left">
                            <div class="text-gray-500 text-xs mb-1">{{ item.label }}</div>
                            <div class="font-medium text-gray-800 text-sm">{{ item.value || '未设置' }}</div>
                        </div>
                    </div>
                </div>
            </el-card>
            
            <!-- 修改密码卡片 - 减少内边距 -->
            <el-card shadow-sm hover:shadow-md transition-shadow>
                <template #header>
                    <div class="border-b border-gray-100 pb-2">
                        <h3 class="text-base font-semibold text-gray-800">修改密码</h3>
                    </div>
                </template>
                
                <el-form :model="form" :rules="rules" label-width="90px" 
                         class="px-3 sm:px-4 py-1" ref="passwordForm">
                    <el-form-item label="原密码" prop="oldPassword">
                        <el-input v-model="form.oldPassword" type="password" 
                                 placeholder="请输入当前使用的密码" show-password />
                    </el-form-item>
                    
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model="form.newPassword" type="password" 
                                 placeholder="8-20位，包含字母和数字" show-password />
                        <div class="password-strength mt-1">
                            <div :class="['strength-bar', passwordStrength >= 1 ? 'active' : '']"></div>
                            <div :class="['strength-bar', passwordStrength >= 2 ? 'active' : '']"></div>
                            <div :class="['strength-bar', passwordStrength >= 3 ? 'active' : '']"></div>
                            <span class="strength-text ml-2 text-xs">
                                {{ strengthText }}
                            </span>
                        </div>
                    </el-form-item>
                    
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input v-model="form.confirmPassword" type="password" 
                                 placeholder="请再次输入新密码" show-password />
                    </el-form-item>
                    
                    <el-form-item class="mt-4">
                        <div class="flex flex-col sm:flex-row justify-center gap-3 w-full">
                            <el-button type="primary" :loading="loading" 
                                       @click="onSubmit" class="flex-1 sm:flex-none">
                                保存修改
                            </el-button>
                            <el-button @click="onCancel" class="flex-1 sm:flex-none">
                                取消
                            </el-button>
                        </div>
                        <div class="text-center mt-2">
                            <router-link to="/forgetPassword" 
                                         class="text-xs text-blue-500 hover:underline">
                                忘记密码？
                            </router-link>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';
import navigation from "../../views/navigation.vue";
import { getStudentBaseInfo } from '@/api/student/personCenter/stuPersonCenter';
import { resetPassword } from '../../api/user';
import { useRouter } from 'vue-router';

const router = useRouter();
const passwordForm = ref(null);
const loading = ref(false);

const userInfo = ref([
    { label: '账号', value: '777777' },
    { label: '性别', value: '男' },
    { label: '姓名', value: '猴子' },
    { label: '学校', value: '贵州人文' },
    { label: '专业', value: '导弹维修' },
    { label: '电话', value: '100' }
]);

const form = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
});

const validatePassword = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入密码'));
    } else if (value.length < 8) {
        callback(new Error('密码长度不能少于8位'));
    } else if (!/[a-zA-Z]/.test(value) || !/\d/.test(value)) {
        callback(new Error('密码必须包含字母和数字'));
    } else {
        callback();
    }
};

const validateConfirmPassword = (rule, value, callback) => {
    if (value !== form.value.newPassword) {
        callback(new Error('两次输入的密码不一致'));
    } else {
        callback();
    }
};

const rules = {
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
    ],
    newPassword: [
        { validator: validatePassword, trigger: 'blur' }
    ],
    confirmPassword: [
        { validator: validateConfirmPassword, trigger: 'blur' }
    ]
};

//密码强度
const passwordStrength = computed(() => {
    const password = form.value.newPassword;
    if (!password) return 0;
    
    let strength = 0;
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
    if (/\d/.test(password) && /[^a-zA-Z0-9]/.test(password)) strength++;
    
    return strength;
});

const strengthText = computed(() => {
    const strength = passwordStrength.value;
    const texts = ['非常弱', '弱', '中等', '强'];
    return texts[strength] || '';
});

const fetchStudentInfo = async () => {
    try {
        const data = await getStudentBaseInfo();
        userInfo.value[0].value = data.account;
        userInfo.value[1].value = data.gender == 1 ? '男' : '女';
        userInfo.value[2].value = data.userName;
        userInfo.value[3].value = data.school || '未设置';
        userInfo.value[4].value = data.major || '未设置';
        userInfo.value[5].value = data.phone || '未设置';
    } catch (error) {
        ElMessage.error('用户信息获取失败，请稍后再试');
    }
};

const onSubmit = async () => {
    try {
        await passwordForm.value.validate();
        loading.value = true;
        
        await resetPassword(form.value.oldPassword, form.value.newPassword);
        ElMessage.success('密码修改成功，请重新登录');
        
        setTimeout(() => {
            router.replace('/login');
        }, 1500);
    } catch (error) {
        if (error.message) {
            ElMessage.error(error.message);
        }
    } finally {
        loading.value = false;
    }
};

const onCancel = () => {
    passwordForm.value.resetFields();
    ElMessage.info('已取消修改');
};

onMounted(() => {
    fetchStudentInfo();
});
</script>

<style scoped>
.password-strength {
    display: flex;
    align-items: center;
    height: 4px;
}

.strength-bar {
    flex: 1;
    height: 100%;
    margin-right: 2px;
    background-color: #e5e7eb;
    transition: all 0.3s;
}

.strength-bar.active {
    background-color: var(--el-color-primary);
}

.strength-bar:nth-child(1).active {
    background-color: #f87171;
}

.strength-bar:nth-child(2).active {
    background-color: #fbbf24;
}

.strength-bar:nth-child(3).active {
    background-color: #4ade80;
}

.strength-text {
    color: #6b7280;
}
.max11{
    margin-top: 70px;
    margin-left: -600px;
}
:deep(.el-card) {
    border-radius: 6px;
}

:deep(.el-card__header) {
    border-bottom: 1px solid #f3f4f6;
    padding: 12px 16px;
}

:deep(.el-form-item__label) {
    color: #4b5563;
    font-weight: 500;
    font-size: 13px;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
    padding: 0 8px;
}

:deep(.el-button) {
    border-radius: 4px;
    padding: 8px 12px;
    font-size: 13px;
}

@media (max-width: 640px) {
    :deep(.el-form-item__label) {
        margin-bottom: 10px;
        width: 100%;
        text-align: left;
    }
    
    :deep(.el-form-item__content) {
        width: 100%;
    }
    
    .max11 {
        margin-left: 0;
    }
}
</style>